﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VideoRentalShop.Model;
using System.Data.Entity;

namespace VideoRentalShop.Controller.Data
{
    public class ClientDataSource : DataSourceBase<Client>
    {
        private OrderDataSource _orderSource;


        public ClientDataSource(MovieDbContext db, OrderDataSource orderSource) : base(db)
        {
            _orderSource = orderSource;
        }


        public DbSet<Client> GetAll()
        {
            return _db.Clients;
        }

        public Client Get(long id)
        {
            return _db.Clients.Find(id);
        }


        public override bool IsValid(Client item)
        {
            return _db.Entry(item).GetValidationResult().IsValid;
        }

        public override bool Add(Client item)
        {
            var entry = _db.Entry<Client>(item);
            var valid = entry.GetValidationResult().IsValid;
            if (valid)
            {
                entry.State = EntityState.Added;
                return Save();
            }

            return valid;
        }

        public override bool Edit(Client item)
        {
            var entry = _db.Entry<Client>(item);
            var valid = entry.GetValidationResult().IsValid;
            if (valid)
            {
                entry.State = EntityState.Modified;
                return Save();
            }

            return valid;
        }

        public bool Check(Client item)
        {
            var orders = item.Orders;
            foreach (var order in orders)
            {
                var details = order.OrderDetails;
                foreach (var detail in details)
                {
                    if (detail.MaxReturnDate <= DateTime.Now && detail.ReturnDate == null)
                    {
                        return false;
                    }
                }
            }

            return true;
        }

        public IEnumerable<OrderDetails> GetHeldMovies(Client client)
        {
            if (client != null)
            {
                var orders = _db.Orders.Where(x => (x.Archived == false) && (x.ClientId == client.Id)).Select(x => x.Id);
                var result = _db.OrderDetails.Where(x => orders.Contains(x.OrderId) && x.ReturnDate == null);

                return result;
            }

            return null;
        }

        public override bool Remove(Client item)
        {
            var result = _db.Clients.Find(item.Id);
            if (result != null)
            {
                _orderSource.Remove(item);
                _db.Entry(result).State = EntityState.Deleted;
                return Save();
            }

            return false;
        }
    }
}
